package com.universityJob.modules.job.task;

import com.google.gson.Gson;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServlet;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import java.net.URL;
import java.net.URLConnection;
import java.util.Map;


/**
 * @author mao on 2021/5/21.
 * @version 1.0 maozhijob@163.com
 */
@Component("recommendTask")
public class RecommendTask implements ITask {
    @Value("${app.appid}")
    private String appid;
    @Value("${app.appsecret}")
    private String appsecret;

    private Logger logger = LoggerFactory.getLogger(getClass());

    private String getConnect(String url) {
        String result = "";
        BufferedReader reader = null;
        try {
            URL con = new URL(url);
            URLConnection urlConnection = con.openConnection();
            urlConnection.connect();
            reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                result += line;
            }
        } catch (IOException e) {
            logger.error("发送Get请求异常，请求获取AccessToken");
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    private Boolean Recommend(String access_token){

        String recommendUrl = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" +
                access_token;

        String connect = getConnect(recommendUrl);
//
//        if ("".equals(connect)){
//
//        }
        return false;

    }

    @Override
    public void run(String params) {
        logger.info("appid 为 {}，appsecret 为 {}",appid,appsecret);
        if (appid.isEmpty() || appsecret.isEmpty()) {
            logger.error("appid 或者 appsecret 为空，请检查!");
            return;
        }
        String accessToken = getConnect("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&" +
                "appid=" + appid + "&secret=" + appsecret + "");
        Gson gson = new Gson();
        Map map = gson.fromJson(accessToken, Map.class);
        String access_token = MapUtils.getString(map, "access_token","");
        String errcode = MapUtils.getString(map, "errcode", "");
        if ("".equals(errcode)){
            logger.error("获取access_token失败，失败码 {}",errcode);
            return;
        }
        if ("".equals("access_token")){
            logger.error("获取access_token失败");
        }else {
            Recommend(access_token);
        }
    }
}
